package com.yix.admin.modules.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.yix.admin.modules.system.entity.SysDept;
import com.yix.admin.modules.system.entity.SysUser;
import com.yix.admin.modules.system.entity.dto.SysDeptDto;
import com.yix.admin.modules.system.entity.mapper.SysDeptMapper;
import com.yix.admin.modules.system.entity.query.SysDeptQuery;
import com.yix.admin.modules.system.repository.SysDeptRepository;
import com.yix.admin.modules.system.repository.SysRoleRepository;
import com.yix.admin.modules.system.repository.SysUserRepository;
import com.yix.admin.modules.system.service.SysDeptService;
import com.yix.common.exception.BadRequestException;
import com.yix.common.utils.*;
import com.yix.common.utils.enums.DataScopeEnum;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author wdx
 * @version 1.0
 * @Description TODO
 * @date 2021/2/2 13:57
 */
@Service
@CacheConfig(cacheNames = "dept")
public class SysDeptServiceImpl implements SysDeptService {

    @Autowired
    private SysDeptRepository sysDeptRepository;
    @Autowired
    private SysUserRepository sysUserRepository;
    @Autowired
    private SysRoleRepository sysRoleRepository;
    @Autowired
    private SysDeptMapper sysDeptMapper;
    @Autowired
    private RedisUtils redisUtils;

    @Override
    public Set<SysDept> findByRoleId(String id) {
        return sysDeptRepository.findByRoleId(id);
    }

    @Override
    public List<SysDept> findByPid(String pid) {
        return sysDeptRepository.findByPid(pid);
    }

    @Override
    public List<String> getDeptChildren(List<SysDept> deptList) {
        List<String> list = new ArrayList<>();
        deptList.forEach(dept -> {
                    if (dept!=null && dept.getEnabled()) {
                        List<SysDept> depts = sysDeptRepository.findByPid(dept.getId());
                        if (deptList.size() != 0) {
                            list.addAll(getDeptChildren(depts));
                        }
                        list.add(dept.getId());
                    }
                }
        );
        return list;
    }

    @Override
    public void download(List<SysDeptDto> deptDtos, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (SysDeptDto deptDTO : deptDtos) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("部门名称", deptDTO.getName());
            map.put("部门状态", deptDTO.getEnabled() ? "启用" : "停用");
            map.put("创建日期", deptDTO.getCreateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public List<SysDeptDto> queryAll(SysDeptQuery criteria, Boolean isQuery) throws Exception {
        Sort sort = new Sort(Sort.Direction.ASC, "sort");
        String dataScopeType = SecurityUtils.getDataScopeType();
        if (isQuery) {
            if(dataScopeType.equals(DataScopeEnum.ALL.getValue())){
                criteria.setPidIsNull(true);
            }
            List<Field> fields = QueryHelp.getAllFields(criteria.getClass(), new ArrayList<>());
            List<String> fieldNames = new ArrayList<String>(){{ add("pidIsNull");add("enabled");}};
            for (Field field : fields) {
                //设置对象的访问权限，保证对private的属性的访问
                field.setAccessible(true);
                Object val = field.get(criteria);
                if(fieldNames.contains(field.getName())){
                    continue;
                }
                if (ObjectUtil.isNotNull(val)) {
                    criteria.setPidIsNull(null);
                    break;
                }
            }
        }
        List<SysDeptDto> list = sysDeptMapper.toDto(sysDeptRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),sort));
        // 如果为空，就代表为自定义权限或者本级权限，就需要去重，不理解可以注释掉，看查询结果
        if(StringUtils.isBlank(dataScopeType)){
            return deduplication(list);
        }
        return list;
    }

    private List<SysDeptDto> deduplication(List<SysDeptDto> list) {
        List<SysDeptDto> deptDtos = new ArrayList<>();
        for (SysDeptDto deptDto : list) {
            boolean flag = true;
            for (SysDeptDto dto : list) {
                if (dto.getId().equals(deptDto.getPid())) {
                    flag = false;
                    break;
                }
            }
            if (flag){
                deptDtos.add(deptDto);
            }
        }
        return deptDtos;
    }

    @Override
    @Cacheable(key = "'id:' + #p0")
    public SysDeptDto findById(String id) {
        SysDept dept = sysDeptRepository.findById(id).orElseGet(SysDept::new);
        ValidationUtil.isNull(dept.getId(),"Dept","id",id);
        return sysDeptMapper.toDto(dept);
    }

    @Override
    public List<SysDeptDto> getSuperior(SysDeptDto deptDto, List<SysDept> depts) {
        if(deptDto.getPid() == null){
            depts.addAll(sysDeptRepository.findByPidIsNull());
            return sysDeptMapper.toDto(depts);
        }
        depts.addAll(sysDeptRepository.findByPid(deptDto.getPid()));
        return getSuperior(findById(deptDto.getPid()), depts);
    }

    @Override
    public Object buildTree(List<SysDeptDto> deptDtos) {
        Set<SysDeptDto> trees = new LinkedHashSet<>();
        Set<SysDeptDto> depts= new LinkedHashSet<>();
        List<String> deptNames = deptDtos.stream().map(SysDeptDto::getName).collect(Collectors.toList());
        boolean isChild;
        for (SysDeptDto deptDTO : deptDtos) {
            isChild = false;
            if (deptDTO.getPid() == null) {
                trees.add(deptDTO);
            }
            for (SysDeptDto it : deptDtos) {
                if (it.getPid() != null && deptDTO.getId().equals(it.getPid())) {
                    isChild = true;
                    if (deptDTO.getChildren() == null) {
                        deptDTO.setChildren(new ArrayList<>());
                    }
                    deptDTO.getChildren().add(it);
                }
            }
            if(isChild) {
                depts.add(deptDTO);
            } else if(deptDTO.getPid() != null &&  !deptNames.contains(findById(deptDTO.getPid()).getName())) {
                depts.add(deptDTO);
            }
        }

        if (CollectionUtil.isEmpty(trees)) {
            trees = depts;
        }
        Map<String,Object> map = new HashMap<>(2);
        map.put("totalElements",deptDtos.size());
        map.put("content",CollectionUtil.isEmpty(trees)? deptDtos :trees);
        return map;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(SysDept resources) {
        resources.setCreaterId(SecurityUtils.getCurrentUserId());
        sysDeptRepository.save(resources);
        // 计算子节点数目
        resources.setSubCount(0);
        // 清理缓存
        updateSubCnt(resources.getPid());
    }

    private void updateSubCnt(String deptId){
        if(deptId != null){
            int count = sysDeptRepository.countByPid(deptId);
            sysDeptRepository.updateSubCntById(count, deptId);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(SysDept resources) {
        // 旧的部门
        String oldPid = findById(resources.getId()).getPid();
        String newPid = resources.getPid();
        if(resources.getPid() != null && resources.getId().equals(resources.getPid())) {
            throw new BadRequestException("上级不能为自己");
        }
        SysDept dept = sysDeptRepository.findById(resources.getId()).orElseGet(SysDept::new);
        ValidationUtil.isNull( dept.getId(),"Dept","id",resources.getId());
        resources.setId(dept.getId());
        resources.setUpdaterId(SecurityUtils.getCurrentUserId());
        sysDeptRepository.save(resources);
        // 更新父节点中子节点数目
        updateSubCnt(oldPid);
        updateSubCnt(newPid);
        // 清理缓存
        delCaches(resources.getId());
    }

    /**
     * 清理缓存
     * @param id /
     */
    public void delCaches(String id){
        List<SysUser> users = sysUserRepository.findByDeptRoleId(id);
        // 删除数据权限
        redisUtils.delByKeys(CacheKey.DATA_USER, users.stream().map(SysUser::getId).collect(Collectors.toSet()));
        redisUtils.del(CacheKey.DEPT_ID + id);
    }

    @Override
    public Set<SysDeptDto> getDeleteDepts(List<SysDept> menuList, Set<SysDeptDto> deptDtos) {
        for (SysDept dept : menuList) {
            deptDtos.add(sysDeptMapper.toDto(dept));
            List<SysDept> depts = sysDeptRepository.findByPid(dept.getId());
            if(depts!=null && depts.size()!=0){
                getDeleteDepts(depts, deptDtos);
            }
        }
        return deptDtos;
    }

    @Override
    public void verification(Set<SysDeptDto> deptDtos) {
        Set<String> deptIds = deptDtos.stream().map(SysDeptDto::getId).collect(Collectors.toSet());
        if(sysUserRepository.countByDepts(deptIds) > 0){
            throw new BadRequestException("所选部门存在用户关联，请解除后再试！");
        }
        if(sysRoleRepository.countByDepts(deptIds) > 0){
            throw new BadRequestException("所选部门存在角色关联，请解除后再试！");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Set<SysDeptDto> deptDtos) {
        for (SysDeptDto deptDto : deptDtos) {
            // 清理缓存
            delCaches(deptDto.getId());
            sysDeptRepository.deleteById(deptDto.getId());
            updateSubCnt(deptDto.getPid());
        }
    }
}
